/**
 * 汽车销售管理系统 - 管理后台JavaScript
 * 
 * 提供侧边栏控制、导航高亮、响应式交互等功能
 */

(function() {
    'use strict';

    // DOM元素
    const sidebar = document.getElementById('sidebar');
    const sidebarToggleDesktop = document.getElementById('sidebarToggleDesktop');
    const sidebarToggleMobile = document.getElementById('sidebarToggle');
    const sidebarOverlay = document.getElementById('sidebarOverlay');
    const mainWrapper = document.querySelector('.main-wrapper');

    // 初始化
    document.addEventListener('DOMContentLoaded', function() {
        initSidebar();
        initNavigation();
        initTooltips();
        initResponsive();
        highlightCurrentPage();
    });

    /**
     * 初始化侧边栏功能
     */
    function initSidebar() {
        // 从localStorage恢复侧边栏状态
        const sidebarCollapsed = localStorage.getItem('sidebarCollapsed') === 'true';
        if (sidebarCollapsed && window.innerWidth >= 992) {
            sidebar.classList.add('collapsed');
            mainWrapper.classList.add('sidebar-collapsed');
        }

        // 桌面端侧边栏切换
        if (sidebarToggleDesktop) {
            sidebarToggleDesktop.addEventListener('click', function() {
                toggleSidebar();
            });
        }

        // 移动端侧边栏切换
        if (sidebarToggleMobile) {
            sidebarToggleMobile.addEventListener('click', function() {
                closeMobileSidebar();
            });
        }

        // 遮罩层点击关闭
        if (sidebarOverlay) {
            sidebarOverlay.addEventListener('click', function() {
                closeMobileSidebar();
            });
        }
    }

    /**
     * 切换侧边栏状态（桌面端）
     */
    function toggleSidebar() {
        const isCollapsed = sidebar.classList.contains('collapsed');
        
        if (isCollapsed) {
            sidebar.classList.remove('collapsed');
            mainWrapper.classList.remove('sidebar-collapsed');
            localStorage.setItem('sidebarCollapsed', 'false');
        } else {
            sidebar.classList.add('collapsed');
            mainWrapper.classList.add('sidebar-collapsed');
            localStorage.setItem('sidebarCollapsed', 'true');
        }
    }

    /**
     * 打开移动端侧边栏
     */
    function openMobileSidebar() {
        sidebar.classList.add('show');
        sidebarOverlay.classList.add('show');
        document.body.classList.add('sidebar-open');
    }

    /**
     * 关闭移动端侧边栏
     */
    function closeMobileSidebar() {
        sidebar.classList.remove('show');
        sidebarOverlay.classList.remove('show');
        document.body.classList.remove('sidebar-open');
    }

    /**
     * 初始化导航功能
     */
    function initNavigation() {
        const navLinks = document.querySelectorAll('.sidebar .nav-link');

        navLinks.forEach(link => {
            link.addEventListener('click', function(e) {
                // 移动端点击导航后关闭侧边栏
                if (window.innerWidth < 992) {
                    setTimeout(() => {
                        closeMobileSidebar();
                    }, 150);
                }
            });
        });

        // 特殊处理带下拉菜单的导航项
        const dropdownToggles = document.querySelectorAll('.sidebar .dropdown-toggle');
        dropdownToggles.forEach(toggle => {
            toggle.addEventListener('click', function(e) {
                // 如果点击的是箭头图标区域，阻止默认跳转，只展开菜单
                const rect = this.getBoundingClientRect();
                const clickX = e.clientX - rect.left;
                const arrowZone = rect.width - 30; // 右边30px区域为箭头区域

                if (clickX > arrowZone) {
                    e.preventDefault();
                    // 只展开/收起菜单
                    const target = this.getAttribute('data-bs-target');
                    const collapseEl = document.querySelector(target);
                    if (collapseEl) {
                        const bsCollapse = new bootstrap.Collapse(collapseEl, {
                            toggle: true
                        });
                    }
                } else {
                    // 点击文字区域，正常跳转
                    // 让默认行为发生（跳转到href）
                }
            });
        });
    }

    /**
     * 高亮当前页面导航
     */
    function highlightCurrentPage() {
        const currentPath = window.location.pathname;
        const navLinks = document.querySelectorAll('.sidebar .nav-link');
        
        navLinks.forEach(link => {
            link.classList.remove('active');
            
            const href = link.getAttribute('href');
            if (href && href !== '#') {
                // 精确匹配或路径前缀匹配
                if (currentPath === href || 
                    (href !== '/' && currentPath.startsWith(href))) {
                    link.classList.add('active');
                }
            }
        });

        // 特殊处理：仪表板页面
        if (currentPath === '/' || currentPath === '/auth/dashboard') {
            const dashboardLink = document.querySelector('[data-page="dashboard"]');
            if (dashboardLink) {
                dashboardLink.classList.add('active');
            }
        }
    }

    /**
     * 初始化工具提示
     */
    function initTooltips() {
        // 为折叠状态下的导航项添加工具提示
        const navLinks = document.querySelectorAll('.sidebar .nav-link');
        
        navLinks.forEach(link => {
            const navText = link.querySelector('.nav-text');
            if (navText) {
                link.setAttribute('data-bs-toggle', 'tooltip');
                link.setAttribute('data-bs-placement', 'right');
                link.setAttribute('title', navText.textContent.trim());
            }
        });

        // 初始化Bootstrap工具提示
        const tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
        tooltipTriggerList.map(function (tooltipTriggerEl) {
            return new bootstrap.Tooltip(tooltipTriggerEl, {
                trigger: 'hover',
                container: 'body'
            });
        });
    }

    /**
     * 初始化响应式功能
     */
    function initResponsive() {
        // 监听窗口大小变化
        window.addEventListener('resize', function() {
            handleResize();
        });

        // 初始化时处理一次
        handleResize();
    }

    /**
     * 处理窗口大小变化
     */
    function handleResize() {
        const width = window.innerWidth;
        
        if (width >= 992) {
            // 桌面端：关闭移动端侧边栏，恢复桌面端状态
            closeMobileSidebar();
            
            // 恢复桌面端侧边栏状态
            const sidebarCollapsed = localStorage.getItem('sidebarCollapsed') === 'true';
            if (sidebarCollapsed) {
                sidebar.classList.add('collapsed');
                mainWrapper.classList.add('sidebar-collapsed');
            } else {
                sidebar.classList.remove('collapsed');
                mainWrapper.classList.remove('sidebar-collapsed');
            }
        } else {
            // 移动端：移除桌面端状态
            sidebar.classList.remove('collapsed');
            mainWrapper.classList.remove('sidebar-collapsed');
        }
    }

    /**
     * 显示加载状态
     */
    function showLoading(element, text = '加载中...') {
        if (element) {
            element.innerHTML = `
                <div class="d-flex align-items-center">
                    <div class="spinner-border spinner-border-sm me-2" role="status">
                        <span class="visually-hidden">Loading...</span>
                    </div>
                    ${text}
                </div>
            `;
            element.disabled = true;
        }
    }

    /**
     * 隐藏加载状态
     */
    function hideLoading(element, originalText) {
        if (element) {
            element.innerHTML = originalText;
            element.disabled = false;
        }
    }

    /**
     * 显示确认对话框
     */
    function showConfirm(message, callback) {
        if (confirm(message)) {
            callback();
        }
    }

    /**
     * 显示成功消息
     */
    function showSuccess(message) {
        showAlert(message, 'success');
    }

    /**
     * 显示错误消息
     */
    function showError(message) {
        showAlert(message, 'danger');
    }

    /**
     * 显示警告消息
     */
    function showWarning(message) {
        showAlert(message, 'warning');
    }

    /**
     * 显示信息消息
     */
    function showInfo(message) {
        showAlert(message, 'info');
    }

    /**
     * 显示警告框
     */
    function showAlert(message, type = 'info') {
        const alertContainer = document.querySelector('.flash-messages') || 
                              document.querySelector('.main-content');
        
        if (alertContainer) {
            const alertElement = document.createElement('div');
            alertElement.className = `alert alert-${type} alert-dismissible fade show`;
            alertElement.innerHTML = `
                <i class="bi bi-${getAlertIcon(type)} me-2"></i>
                ${message}
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            `;
            
            if (alertContainer.classList.contains('flash-messages')) {
                alertContainer.appendChild(alertElement);
            } else {
                alertContainer.insertBefore(alertElement, alertContainer.firstChild);
            }
            
            // 自动消失（成功消息）
            if (type === 'success') {
                setTimeout(() => {
                    alertElement.remove();
                }, 5000);
            }
        }
    }

    /**
     * 获取警告框图标
     */
    function getAlertIcon(type) {
        const icons = {
            'success': 'check-circle',
            'danger': 'exclamation-triangle',
            'warning': 'exclamation-circle',
            'info': 'info-circle'
        };
        return icons[type] || 'info-circle';
    }

    // 暴露全局方法
    window.AdminJS = {
        showLoading,
        hideLoading,
        showConfirm,
        showSuccess,
        showError,
        showWarning,
        showInfo,
        openMobileSidebar,
        closeMobileSidebar
    };

})();
